/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.modules.api.service.impl.MattersServiceImpl.java
 * <p>
 * 类产生时间: 2014-6-18 0018 下午 17:47
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.modules.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.util.FileUtils;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.StringUtils;
import com.oceansoft.mobile.econsole.modules.api.entity.Consult;
import com.oceansoft.mobile.econsole.modules.api.entity.ProgressResult;
import com.oceansoft.mobile.econsole.modules.api.entity.SFZProgressResult;
import com.oceansoft.mobile.econsole.modules.api.entity.Xsjb;
import com.oceansoft.mobile.econsole.modules.api.persistence.IMattersMapper;
import com.oceansoft.mobile.econsole.modules.api.service.IMattersService;
import com.oceansoft.mobile.econsole.modules.ascproject.entity.MydEvaluation;
import com.oceansoft.mobile.econsole.modules.ascproject.persistence.IProjectMapper;
import com.oceansoft.mobile.econsole.modules.base.entity.ApiPager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.complaint.persistence.IComplaintMapper;
import com.oceansoft.mobile.econsole.modules.jlwt.entity.*;
import com.oceansoft.mobile.econsole.modules.jlwt.persistence.*;
import com.oceansoft.mobile.econsole.modules.member.persistence.IWtMemberMapper;
import com.oceansoft.mobile.econsole.modules.weixin.entity.PoliceClass;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.taglibs.standard.tag.common.core.Util;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 办事接口业务组件实现类
 *
 * @author: chenw
 * @time: 2014-6-18 0018 下午 17:47
 */
@Service
public class MattersServiceImpl extends CacheBaseService implements IMattersService {

    private Logger logger = LoggerFactory.getLogger(MattersServiceImpl.class);

    @Resource
    private IProjectCaseMapper projectCaseMapper;
    @Resource
    private IConsultMapper consultMapper;
    @Resource
    private IAdvisorMapper advisorMapper;
    @Resource
    private IWtMemberMapper wtMemberMapper;
    @Resource
    private IAnswerMapper answerMapper;
    @Resource
    private ICaseMeterialMapper caseMeterialMapper;
    @Resource
    private IProjectMapper projectMapper;
    @Resource
    private IComplaintMapper complaintMapper;
    @Resource
    private IMattersMapper mattersMapper;
    @Resource
    private ICaseBasisMapper caseBasisMapper;

   /* @Override
    public Result loadAllPoliceCatalog() throws IOException {
        String url = super.configInfo.getGAApiUrl("CaseCenter/CaseCondition.aspx");
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        String resp = HttpClientUtil.doGet(url);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
            if (succ) {
                JSONArray array = data.getJSONArray("data");
                super.cache(url, array, 1.0f);
                return new Result(Result.SUCC, array);
            } else {
                return new Result(Result.FAILURE, data.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂无数据");
    }*/


    @Override
    public Result loadAllPoliceCatalog() throws IOException {


//        String url = "app:case:jzlb";
//
//        if (super.exists(url)) {
//            return new Result(Result.SUCC, super.getObject(url));
//        }
        //接口:获取所有警钟 http://172.17.100.132:9008/matters/pccs
//        List<CaseObject> caseObject=projectCaseMapper.getCaseObject();
        String res = HttpClientUtil.doGet(configInfo.getServiceInterfaceAddress() + "/matters/pccs");
//                String res = HttpClientUtil.doGet("http://172.17.100.132:9008/matters/pccs");
        JSONObject object = JSON.parseObject(res);
        List<PoliceClass> caseObject = JSON.parseArray(object.getString("data"), PoliceClass.class);
        if (caseObject != null) {
//            super.cache(url, caseObject, 1.0f);
            return new Result(Result.SUCC, caseObject);

        }

        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    public Result loadAllPoliceCatalogAll() throws IOException {


        String url = "app:case:jzlball";

        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        List<CaseObject> caseObject = projectCaseMapper.getCaseObjectAll();
        if (caseObject != null) {
            super.cache(url, caseObject, 1.0f);
            return new Result(Result.SUCC, caseObject);

        }

        return new Result(Result.FAILURE, "暂无数据");
    }


    public Result loadAllBureau() throws IOException {
        String url = super.configInfo.getGAApiUrl("CaseCenter/Unit.aspx", "iswindow", "0");
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        String resp = HttpClientUtil.doGet(url);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
            if (succ) {
                JSONArray array = data.getJSONArray("data");
                super.cache(url, array, 1.0f);
                return new Result(Result.SUCC, array);
            } else {
                return new Result(Result.FAILURE, data.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    public Result loadDepartments(String bureauId) throws IOException {
        String url = super.configInfo.getGAApiUrl("CaseCenter/Unit.aspx", "pid", bureauId, "iswindow", "1");
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        String resp = HttpClientUtil.doGet(url);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
            if (succ) {
                JSONArray array = data.getJSONArray("data");
                super.cache(url, array, 1.0f);
                return new Result(Result.SUCC, array);
            } else {
                return new Result(Result.FAILURE, data.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    public Result loadMattersByCondition(Map<String, String> params) throws IOException {
        String url = formatUrl(super.configInfo.getGAApiUrl("CaseCenter/CaseList.aspx"), params);
        //  params.put("CaseName", "边境管理通行证办理");
        //  System.out.println("====>URL==>\n" + url + "\n\n");
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        String resp = HttpClientUtil.doGet(url);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
                JSONObject data = new JSONObject();
                data.put("list", respData.getJSONObject("data").getJSONArray("ds1"));
                data.put("totalPage", respData.getJSONObject("data").getJSONArray("ds").getJSONObject(0).getInteger("Column1"));
                super.cache(url, data, 1.0f);
                return new Result(Result.SUCC, data);
            } else {
                return new Result(Result.FAILURE, respData.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    public Result loadPoliceStations(String bureauId) throws IOException {
        String url = super.configInfo.getGAApiUrl("CaseCenter/Unit.aspx", "pid", bureauId, "iswindow", "2");
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        String resp = HttpClientUtil.doGet(url);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
            if (succ) {
                JSONArray array = data.getJSONArray("data");
                super.cache(url, array, 1.0f);
                return new Result(Result.SUCC, array);
            } else {
                return new Result(Result.FAILURE, data.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    public Result loadAppointmentPage(Map<String, String> params) throws IOException {
        String url = formatUrl(super.configInfo.getGAApiUrl("CaseCenter/GetYYCaseList.aspx"), params);
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        String resp = HttpClientUtil.doGet(url);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
                JSONObject data = new JSONObject();
                data.put("list", respData.getJSONObject("data").getJSONArray("ds1"));
                data.put("totalPage", respData.getJSONObject("data").getJSONArray("ds").getJSONObject(0).getInteger("Column1"));
                super.cache(url, data, 1.0f);
                return new Result(Result.SUCC, data);
            } else {
                return new Result(Result.FAILURE, respData.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    public Result loadMatterDetail(int deptType, final String deptId, final String matterId) {
        final String url = String.format("http://www.gaj2.suzhou.gov.cn/wsbsdt/Aspx/WorkProcess/CaseInfo.aspx?CaseGuid=%s&bm=%s", matterId, 1 == deptType ? -1 : deptId);
        if (exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        } else {
            try {
                final Document doc = Jsoup.connect(url).timeout(6000).get();
                //事项基本信息
                final Elements tables = doc.getElementsByTag("table");
                final Elements tds = tables.get(1).getElementsByTag("td");
                JSONObject data = new JSONObject() {{
                    put("title", tables.get(0).text());
                    put("spzt", tds.get(1).text());
                    put("fdqx", tds.get(3).text());
                    put("sxxz", tds.get(5).text());
                    put("bldd", tds.get(7).text());
                    put("bjlx", tds.get(9).text());
                    put("blsj", tds.get(11).text());
                    put("cnqx", tds.get(13).text());
                    put("ckdh", tds.get(15).text());
                    put("bsxz", doc.getElementById("tdxf").text());//办事须知
                    Element xkyj_ele = doc.getElementById("gvPursuant");
                    put("xkyj", null != xkyj_ele ? xkyj_ele.text() : ""); //许可依据
                    Elements tds = doc.getElementById("divtag1").getElementsByTag("td");
                    StringBuilder sqcl_str = new StringBuilder();
                    int _index = 0;
                    for (Element td : tds) {
                        String txt = td.text().trim();
                        if (txt.length() > 0) {
                            if ("表格".equals(txt))
                                continue;
                            if (_index > 0) {
                                sqcl_str.append("<br>");
                            }
                            sqcl_str.append(txt);
                        }
                        _index++;
                    }
                    put("sqcl", sqcl_str.toString());//申请材料
                    put("lct", "http://www.gaj2.suzhou.gov.cn/wsbsdt/Aspx/WorkProcess/CaseImage.aspx?bm=" + deptId + "&CaseGuid=" + matterId);//流程图
                }};
                super.cache(url, data, 1.0f);
                return new Result(Result.SUCC, data);
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(Result.FAILURE, "加载网页数据出错");
            }
        }
    }

    @Override
    public Result loadReservationGuid(final String matterId, int policeType) {
        final String url = String.format("http://www.gaj2.suzhou.gov.cn/wsbsdt/Aspx/WorkProcess/CaseInfo.aspx?CaseGuid=%s&bm=-1&stype=%d&action=appyyinfo", matterId, policeType);
        if (exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        } else {
            try {
                final Document doc = Jsoup.connect(url).timeout(6000).get();
                //事项基本信息
                final Elements tables = doc.getElementsByTag("table");
                final Elements tds = tables.get(1).getElementsByTag("td");
                JSONObject data = new JSONObject() {{
                    put("title", tables.get(0).text());
                    put("spzt", tds.get(1).text());
                    put("fdqx", tds.get(3).text());
                    put("sxxz", tds.get(5).text());
                    put("bldd", tds.get(7).text());
                    put("bjlx", tds.get(9).text());
                    put("blsj", tds.get(11).text());
                    put("cnqx", tds.get(13).text());
                    put("ckdh", tds.get(15).text());
                    put("bsxz", doc.getElementById("tdxf").text());//办事须知
                    Element xkyj_ele = doc.getElementById("gvPursuant");
                    put("xkyj", null != xkyj_ele ? xkyj_ele.text() : ""); //许可依据
                    Elements tds = doc.getElementById("divtag1").getElementsByTag("td");
                    StringBuilder sqcl_str = new StringBuilder();
                    int _index = 0;
                    for (Element td : tds) {
                        String txt = td.text().trim();
                        if (txt.length() > 0) {
                            if (_index > 0) {
                                sqcl_str.append("<br>");
                            }
                            sqcl_str.append(txt);
                        }
                        _index++;
                    }
                    put("sqcl", sqcl_str.toString());//申请材料
                    put("lct", "http://www.gaj2.suzhou.gov.cn/wsbsdt/Aspx/WorkProcess/CaseImage.aspx?bm=-1&CaseGuid=" + matterId);//流程图
                }};
                super.cache(url, data, 1.0f);
                return new Result(Result.SUCC, data);
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(Result.FAILURE, "加载数据失败");
            }
        }
    }

    /**
     * 办件进度
     *
     * @param csee_id 办件编号
     * @return Result
     *//*
    @Override
    public Result loadDoScheduleDetail(String csee_id) throws IOException {
        String url = super.configInfo.getGAApiUrl("SearchCenter/Projectsearch.aspx", "probid", csee_id);
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        //重新请求一次并返回结果
        String resp = HttpClientUtil.doGet(url);
        //判断是否为空
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
            //是否请求成功
            if (succ) {
                //获取数据array
                JSONObject _data = data.getJSONArray("data").getJSONObject(0);
                _data.put("UnitAttribute", "1".equals(_data.get("UnitAttribute")) ? "个人" : "企业");
                _data.put("ProjectStatus", getCaseProjectStatus(Integer.parseInt(_data.get("ProjectStatus") + "")));
                //加入到缓存1分钟
                super.cache(url, _data, 1.0f);
                //返回结果集
                return new Result(Result.SUCC, _data);
            } else {
                //succ失败返回错误信息
                return new Result(Result.FAILURE, data.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂时无数据");
    }*/


    /**
     * 办件进度
     *
     * @param caseId 办件编号
     * @return Result
     */
    @Override
    public Result loadDoScheduleDetail(String caseId) throws IOException {

        /*ProjectCaseState projectCaseState = projectCaseMapper.getProjectCaseStateByBillId(csee_id);

        if(projectCaseState !=null) {
            if(projectCaseState.getProjectStatus() !=null) {
                projectCaseState.setProjectStatus(getCaseProjectStatus(Integer.parseInt(projectCaseState.getProjectStatus())));
            }
            if(projectCaseState.getUnitAttribute()!=null) {
                projectCaseState.setUnitAttribute("1".equals(projectCaseState.getUnitAttribute()) ? "个人" : "企业");
            }
            return new Result(Result.SUCC, projectCaseState);
        }
        else
        {
            return new Result(Result.FAILURE, "暂时无数据");
        }*/
        List<ProgressResult> list = mattersMapper.loadDoScheduleDetail(caseId);
        if (null != list && 0 < list.size()) {
            return new Result(Result.SUCC, list.get(0));
        }
        return new Result(Result.FAILURE);
    }
    /**
     * 网上办件进度
     *
     * @param caseId 办件编号
     * @return Result
     */
    @Override
    public Result wsScheduleDetail(String caseId) throws IOException {
        String url = configInfo.getServiceInterfaceAddress() + "/tasks/tsk/"+caseId;

        JSONObject object = JSON.parseObject(HttpClientUtil.doGet(url));
        System.out.println("apiPager.getList()="+HttpClientUtil.doGet(url));

        if(null!= object.getJSONObject("data")){
            return new Result(Result.SUCC,object.getJSONObject("data"));
        }

        return new Result(Result.FAILURE);
    }




    /**
     * 居住证办理进度
     *
     * @param idnum 身份证号
     * @return Result
     */
    @Override
    public Result loadPermitScheduleDetail(String idnum) throws IOException {
        return getResult(super.configInfo.getGAApiUrl("SearchCenter/JZZJDsearch.aspx", "idnum", idnum));
    }

    /**
     * 居住证办办理地点
     *
     * @param jdmc 街道名称
     * @param sqmc 社区名称
     * @return Result
     */
    @Override
    public Result loadPermitSiteDetail(String jdmc, String sqmc) throws IOException {
        String url = super.configInfo.getGAApiUrl("SearchCenter/JZZDDsearch.aspx", "jdmc", jdmc, "sqmc", sqmc);
        return getResult(url);
    }

    /**
     * 身份证办理进度
     *
     * @param idnum 身份证号
     * @return Result
     */
    @Override
    public Result loadIdCardScheduleDetail(String idnum) throws IOException {
        /*String url = super.configInfo.getGAApiUrl("SearchCenter/SFZJDsearch.aspx", "idnum", idnum, "caseid", caseid);
        return getResult(url);*/
        List<SFZProgressResult> list = mattersMapper.loadIdCardScheduleDetail(idnum);
        if (null != list && 0 < list.size()) {
            return new Result(Result.SUCC, list.get(0));
        }
        return new Result(Result.FAILURE);
    }

    /**
     * 案件信息
     *
     * @param idnum  身份证号
     * @param lawnum 接警编号
     * @return Result
     */
    @Override
    public Result loadCaseDetail(String idnum, String lawnum) throws IOException {
        String url = super.configInfo.getGAApiUrl("SearchCenter/AJsearch.aspx", "idnum", idnum, "lawnum", lawnum);
        return getResult(url);
    }

    /**
     * 根据url请求返回结果
     *
     * @param url 请求的webservice地址
     * @return Result
     */
    public Result getResult(String url) throws IOException {
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        //重新请求一次并返回结果
        String resp = HttpClientUtil.doGet(url);
        //判断是否为空
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
            //是否请求成功
            if (succ) {
                //获取数据array
                JSONArray array = data.getJSONArray("data");
                //加入到缓存1分钟
                //super.cache(url, array.getJSONObject(0), 1.0f);
                //返回结果集
                return new Result(Result.SUCC, array.getJSONObject(0));
            } else {
                //succ失败返回错误信息
                return new Result(Result.FAILURE, data.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂时无数据");
    }

    /**
     * 根据url请求返回结果 【取所有结果】
     *
     * @param url 请求的webservice地址
     * @return Result
     */
    public Result getAllResult(String url) throws IOException {
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        //重新请求一次并返回结果
        String resp = HttpClientUtil.doGet(url);
        //判断是否为空
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
            //是否请求成功
            if (succ) {
                //获取数据array
                JSONArray array = data.getJSONArray("data");
                //加入到缓存1分钟
                super.cache(url, array, 1.0f);
                //返回结果集
                return new Result(Result.SUCC, array);
            } else {
                //succ失败返回错误信息
                return new Result(Result.FAILURE, data.getString("msg"), "加载失败");
            }
        }
        return new Result(Result.FAILURE, "暂时无数据");
    }

    /**
     * 提交货车申报
     *
     * @param report 申报数据
     * @return Result
     */
    @Override
    public Result submitTruckReport(JSONObject report) {
        return null;
    }

    /**
     * 律师事项申报
     *
     * @param lawyerReport 申报数据
     * @return Result
     */
    @Override
    public Result submitLawyerReport(JSONObject lawyerReport) throws IOException {
        String url = super.configInfo.getGAApiUrl("ReportPage/ReportLS.aspx");
        return HttpClientUtil.doGAUrlPost(url, lawyerReport);
    }

    /**
     * 提交出入境预约
     *
     * @param bespeak 数据
     * @return Result
     */
    @Override
    public Result submitBespeakExist(JSONObject bespeak) throws IOException {
        return HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("ReportPage/ReportYYCRJ.aspx"), bespeak);
    }

    /**
     * 提交特警项目预约
     *
     * @param bespeak 预约实体
     * @return Result
     */
    public Result submitBespeakPolice(JSONObject bespeak) throws IOException {
        return HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("ReportPage/ReportTJ.aspx"), bespeak);
    }

    /**
     * 咨询列表
     *
     * @param params 参数
     * @return Result
     */
    @Override
    public Result loadConsultList(Map<String, String> params) throws IOException {

        int startIndex = 0;
        int endIndex = 10;
        int pageSize = 10;
        if (StringUtils.isNotBlank(params.get("pagesize")) && StringUtils.isNotBlank((params.get("pageindex")))) {
            pageSize = Integer.parseInt(params.get("pagesize") + "");
            int pageIndex = Integer.parseInt(params.get("pageindex") + "");
            startIndex = (pageIndex * pageSize) - (pageSize - 1);
            endIndex = pageIndex * pageSize;
        }
        params.put("startIndex", String.valueOf(startIndex));
        params.put("endIndex", String.valueOf(endIndex));
        //+"&kw="+params.get("keywords")
        String url=configInfo.getServiceInterfaceAddress()+"/consults/page?ps=10&pi="+params.get("pageindex");
        if(!Strings.isNullOrEmpty(params.get("keywords"))){
            url+="&kw="+params.get("keywords");
        }
//        String res= HttpClientUtil.doGet("http://172.17.100.132:9010/consults/page?ps=10&pi="+params.get("pageindex")+"&kw="+params.get("keywords"));
        String res= HttpClientUtil.doGet(url);
        JSONObject object = JSON.parseObject(res);
        ApiPager apiPager = JSON.parseObject(object.getString("data"), ApiPager.class);
        int totalPage=apiPager.getTotalPage();


//        List<ConsulaObj> lstConsulaObj = consultMapper.getConsulObjs(params);
//        int recordCount = consultMapper.getConsulObjsCount(params);
        if (totalPage > 0) {
            JSONObject data = new JSONObject();
            data.put("list", apiPager.getList());
            data.put("totalPages", apiPager.getTotalPage());
            // super.cache(url, data, 3L * 60L);
            return new Result(Result.SUCC, data);
        }

        return new Result(Result.FAILURE, "暂无数据");
    }

    /*
    *//**
     * 咨询列表
     *
     * @param params 参数
     * @return Result
     *//*
    @Override
    public Result loadConsultList(Map<String, String> params) throws IOException {
        String url = formatUrl(super.configInfo.getGAApiUrl("Consultation/ConsultaList.aspx"), params);
        logger.info("\n");
        logger.info("咨询列表::" + url);
        logger.info("\n");
        if (!StringUtils.isNotBlank(params.get("uid")) && super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        String resp = HttpClientUtil.doGet(url);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
                JSONObject data = new JSONObject();
                int pagesize = Integer.parseInt(params.get("pagesize") + "");
                int total = respData.getJSONObject("data").getJSONArray("Table1").getJSONObject(0).getInteger("RecordCount");
                int totalPages = total % pagesize == 0 ? total / pagesize : total / pagesize + 1;

                JSONArray list = respData.getJSONObject("data").getJSONArray("ds");
                for(int i = 0; i < list.size(); i++){
                    JSONObject o = list.getJSONObject(i);
                    o.put("LocalIP","");
                }

                data.put("list", list);
                data.put("totals", totalPages);
                super.cache(url, data, 3L * 60L);
                return new Result(Result.SUCC, data);
            } else {
                return new Result(Result.FAILURE, respData.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂无数据");
    }*/

    /**
     * 回答信息
     *
     * @param qid 问题id
     * @return Result
     */
    @Override
    public Result loadAnswer(String qid) throws IOException {
        String url = "Answer";

        ConsulaObj consulaObj = answerMapper.getAnswerByQid(qid);
        if (consulaObj != null) {
            return new Result(Result.SUCC, consulaObj);
        }


        return new Result(Result.FAILURE, "暂无数据");
    }


  /*  *//**
     * 回答信息
     *
     * @param qid 问题id
     * @return Result
     *//*
    @Override
    public Result loadAnswer(String qid) throws IOException {
        String url = super.configInfo.getGAApiUrl("Consultation/Answer.aspx", "qid", qid);
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        String resp = HttpClientUtil.doGet(url);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
            if (succ) {
                JSONArray query = data.getJSONObject("data").getJSONArray("ds");
                super.cache(url, query.getJSONObject(0), 1.0f);
                return new Result(Result.SUCC, query.getJSONObject(0));
            } else {
                return new Result(Result.FAILURE, data.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂无数据");
    }*/

  /*  *//**
     * 咨询问题提交
     *
     * @return Result
     *//*
    @Override
    public Result submitQuestion(JSONObject question) throws IOException {
        return HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("Consultation/Consulta.aspx"), question);
    }*/


    /**
     * 咨询问题提交
     *
     * @return Result
     */
    @Override
    public Result submitQuestion(JSONObject question) throws IOException {

        Advisor obj = new Advisor();
        String uid = question.get("uid").toString();//咨询人guid
        String msgtext = question.get("msgtext").toString();//咨询内容

        String advisoryTop = question.get("advisoryTop").toString();//咨询主题
        String isPublic = question.get("isPublic").toString();//是否公开（0:公开   1：不公开）
        String userName = question.get("userName").toString();//咨询人姓名
        String advisoryMobile = question.get("advisoryMobile").toString();//咨询人联系电话

        String advisoryCaseGuid = question.get("advisoryCaseGuid").toString();//咨询事项guid
//        String advisoryOrgId = question.get("advisoryOrgId").toString();//要咨询部门ID
        String advisoryOrgId = "230600000000";//咨询部门ID写死
//        String advisoryOrgName = question.get("advisoryOrgName").toString();//要咨询部门名称
        String advisoryOrgName = "大庆市公安局";//咨询部门写死

        String isAnonymous = question.get("isAnonymous").toString();//0:匿名   1：实名

        SimpleDateFormat sf = new SimpleDateFormat("yyMMdd");
        String perfix = sf.format(new Date());
        int max = advisorMapper.getMaxAdvisor(perfix);
        String pt = question.get("pt").toString();
        //String fqNumber=perfix+String.format("%04d", max);
        String fqNumber = pt;//平台代码
        // 组织机构2到8位
        if (advisoryOrgId != null && advisoryOrgId.length() > 8) {
            fqNumber += advisoryOrgId.substring(2, 8);
        }
        // 日期后6位
        fqNumber += sf.format(new Date());
        // 警种
        fqNumber += "23";
        // 4位流水号
        fqNumber += String.format("%04d", max);

        obj.setGuid(UUID.randomUUID().toString());
        obj.setAdvisory_Guid(uid);
        obj.setAdvisory_User(userName); //咨询人姓名字段改存登录用户名
//        obj.setAdvisory_User(advisoryMobile);
        obj.setAdvisory_Time(new Date());
        obj.setAdvisoryNo(fqNumber);
        obj.setAdvisorTop(advisoryTop);
        obj.setAdvisory(msgtext);
        obj.setTemp1(isPublic);
        obj.setAdvisory_CaseGuid(advisoryCaseGuid);
        obj.setAdvisoryMobile(advisoryMobile);
        obj.setAdvisory_OrgId(advisoryOrgId);
        obj.setaAdvisory_OrgName(advisoryOrgName);
        obj.setIsAnonymous(isAnonymous);

        try {
            /*WtMember pascMember = wtMemberMapper.getWtMemberByUserGuid(uid);
            obj.setAdvisorTop(null);
            obj.setAdvisory_User(pascMember.getUserName());*/
            obj.setTemp4("0");
            advisorMapper.SaveAdvisor(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "提交失败!");
        }

        return new Result(Result.SUCC, "提交成功!");


    }

    @Override
    public Result askQuestion(JSONObject question) {
        System.out.println(question.toJSONString());
        String url = configInfo.getServiceInterfaceAddress() + "/consults/consult/";
//        url = "http://172.17.100.132:9010/consults/consult";
        String res = null;
        try {
            res = HttpClientUtil.post(url, question);
        } catch (IOException e) {
            logger.error("数据调用借口错误", e);
        }
        return new Result(JSON.parseObject(res).getBooleanValue("succ"));
    }

    //货车通行证
    @Override
    public Result loadTruckPermitInfo(String permitNo, String permitCode, String permitPsd) throws IOException {
        return getResult(super.configInfo.getGAApiUrl("SearchCenter/HCTXZsearch.aspx", "txzbh", permitNo, "txzwym", permitCode, "txtmm", permitPsd));
    }

    //临时通行证
    @Override
    public Result loadInterimPermitInfo(String permitCode) throws IOException {
        return getResult(super.configInfo.getGAApiUrl("SearchCenter/LSTXZsearch.aspx", "txzwym", permitCode));
    }

    /**
     * 根据派出所id查找警务室列表
     *
     * @param pid 派出所id
     * @return Result
     */
    @Override
    public Result loadPoliceOfficeByStation(String pid) throws IOException {
        String url = super.configInfo.getGAApiUrl("CaseCenter/PoliceStation.aspx", "pid", pid);
        if (super.exists(url)) {
            return new Result(Result.SUCC, super.getObject(url));
        }
        //重新请求一次并返回结果
        String resp = HttpClientUtil.doGet(url);
        //判断是否为空
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(data.getString("succ"));
            //是否请求成功
            if (succ) {
                //获取数据array
                JSONArray array = data.getJSONArray("data");
                //加入到缓存1分钟
                super.cache(url, array, 1.0f);
                //返回结果集
                return new Result(Result.SUCC, array);
            } else {
                //succ失败返回错误信息
                return new Result(Result.FAILURE, data.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂时无数据");
    }

    /**
     * 警务室信息
     *
     * @param alarmId 警务室id
     * @return Result
     */
    @Override
    public Result loadAlarmRoomInfo(String alarmId) throws IOException {
        return getResult(super.configInfo.getGAApiUrl("CaseCenter/PoliceDetail.aspx", "jwsid", alarmId));
    }

    /**
     * 警务室信息
     *
     * @param alarmName 警务室id
     * @return Result
     */
    @Override
    public Result loadAlarmRoomInfoByName(String alarmName) throws IOException {
        return getResult(super.configInfo.getGAApiUrl("CaseCenter/PoliceDetailByName.aspx", "jwsname", Util.URLEncode(alarmName, "utf-8")));
    }

    @Override
    public Result sendMsg(JSONObject bespeak) throws IOException {
        return getResult(super.configInfo.getGAApiUrl("Message.aspx", "hm", bespeak.getString("tel"), "msg", Util.URLEncode(bespeak.getString("msg"), "utf-8")));
    }

    @Override
    public Result sendMsg(String tel, String msg) throws IOException {
        JSONObject obj = new JSONObject();
        obj.put("tel", tel);
        obj.put("msg", msg);
        return sendMsg(obj);
    }

    /**
     * 办件列表
     *
     * @param params 参数
     * @return Rsult
     */
    @Override
    public Result myProject(Map<String, String> params) throws IOException {
        String url = formatUrl(super.configInfo.getGAApiUrl("PersonCenter/MyProject.aspx"), params);
        String resp = HttpClientUtil.doGet(url);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject respData = JSON.parseObject(resp);
            boolean succ = "True".equalsIgnoreCase(respData.getString("succ"));
            if (succ) {
                JSONObject data = new JSONObject();
                int pagesize = Integer.parseInt(params.get("pagesize") + "");
                int total = respData.getJSONObject("data").getJSONArray("ds").getJSONObject(0).getInteger("Column1");
                int totalPages = total % pagesize == 0 ? total / pagesize : total / pagesize + 1;
                data.put("list", respData.getJSONObject("data").getJSONArray("ds1"));
                data.put("totals", totalPages);
                super.cache(url, data, 1.0f);
                return new Result(Result.SUCC, data);
            } else {
                return new Result(Result.FAILURE, respData.getString("msg"));
            }
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    public Result projectMyd(JSONObject bespeak) throws IOException {
        //Prjid办件序号     type  -1 市局 2分局     mydcontent评价    mydtype  1非常满意  2基本满意  3不满意
        return HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("PersonCenter/ProjectMYD.aspx"), bespeak);
    }

    @Override
    @Transactional
    public Result projectMyd(MydEvaluation mydEvaluation) {
        mydEvaluation.setGuid(UUID.randomUUID().toString());
        mydEvaluation.setCreateTime(new Date());

        if (mydEvaluation.getEvaluaTionType().equals("1")) {
            //更新咨询表为已评价
            // 20160504 评价后不修改咨询表状态，评价后光闸会再次同步此数据，会覆盖掉内网分发给的部门
            //consultMapper.updateConsultComment(mydEvaluation.getPrjGuid());
        } else if (mydEvaluation.getEvaluaTionType().equals("2")) {
            // 更新办件表为已评价,20160607 评价后光闸会再次同步此数据，会覆盖掉内网数据，造成二次审批
            // projectMapper.updateProjectComment(mydEvaluation.getPrjGuid());
        } else if (mydEvaluation.getEvaluaTionType().equals("3")) {
            // 更新投诉表为已评价,20160607 评价后光闸会再次同步此数据，会覆盖掉内网数据，造成二次审批
            // complaintMapper.updateComplaintComment(mydEvaluation.getPrjGuid());
        }

        // 此处应判断是否评价过
        // 咨询/办件 编号
        String prjGuid = mydEvaluation.getPrjGuid();
        // xhb
        int rt = 0;
        try {
            String num = projectMapper.getPrjNum(prjGuid);
            if ("0".equals(num) || num == null) {
                rt = projectMapper.projectMyd(mydEvaluation);
            } else {
                return new Result(Result.FAILURE, "您已评价过，请勿重复评价");
                //rt = projectMapper.updateEvaluationgrade(mydEvaluation);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (rt > 0) {
            return new Result(Result.SUCC, "评价成功");
        }
        return new Result(Result.FAILURE, "满意度评价失败");
    }

    @Override
    public Result undoProject(JSONObject bespeak) throws IOException {
        //Prjid办件序号     type  -1 市局 2分局
        return HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("PersonCenter/UndoPorject.aspx"), bespeak);
    }

    @Override
    public Result projectDetail(String prjid, String type) throws IOException {
        return getResult(super.configInfo.getGAApiUrl("PersonCenter/ProjectDetail.aspx", "Prjid", prjid, "type", type));
    }

    /**
     * 办件状态转化
     *
     * @param projectSatus 办件状态22222
     * @return String
     */
    public String getCaseProjectStatus(int projectSatus) {
        switch (projectSatus) {
            case 0:
                return "已保存";
            case 1:
                return "待预审";
            case 2:
                return "已预审";
            case 3:
                return "已受理";
            case 4:
                return "已审核";
            case 5:
                return "已回传";
            case 51:
                return "接收成功";
            case 6:
                return "已上报";
            case 7:
                return "已收费";
            case 8:
                return "已批复";
            case 9:
                return "已办结";
            case 10:
                return "已补办";
            case 11:
                return "转异常";
            case 12:
                return "转答复";
            case 13:
                return "已退回";
            case 14:
                return "已撤销";
            default:
                return "";
        }
    }

    /**
     * 格式化URL参数
     *
     * @param url    原始URL
     * @param params 参数集合
     * @return String 格式化后URL
     */
    private String formatUrl(String url, Map<String, String> params) {
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, "UTF-8"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return url;
    }

    @Override
    public Result loadPassportYZDD() throws IOException {
        String url = super.configInfo.getGAApiUrl("ReportPage/ReportTXZGXDD.aspx");
        return getAllResult(url);
    }

    @Override
    public Result loadPassportYZWP() throws IOException {
        String url = super.configInfo.getGAApiUrl("ReportPage/ReportTXZYZWP.aspx");
        return getAllResult(url);
    }

    @Override
    public Result savePassport(JSONObject passport) throws IOException {
        return HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("ReportPage/ReportTXZ.aspx"), passport);
    }

    @Override
    public Result saveLine(JSONObject line) throws IOException {
        return HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("ReportPage/ReportTXZ.aspx"), line);
    }

    @Override
    public Result getPassportFiles() throws IOException {
        return getAllResult(super.configInfo.getGAApiUrl("CaseCenter/CaseMaterial.aspx", "caseguid", "687a63ec-7e65-41e3-b90a-7febc72dc9a4", "type", "-1"));
    }

    @Override
    public Result uploadPassportFiles(File file, String materialGuid, String userGuid, String caseGuid, String projectGuid) throws Exception {
        String url = super.configInfo.getGAApiUrl("ReportPage/Upload.aspx", "materialGuid", materialGuid, "userGuid", userGuid, "caseGuid", caseGuid, "projectGuid", projectGuid);
        int statusCode = doPostUpload(url, file);
        if (statusCode == HttpStatus.SC_OK)
            return new Result(Result.SUCC, "上传成功");
        return new Result(Result.FAILURE, "上传失败,HttpStatusCode:" + statusCode);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result savePassportPhoto(String localHostIP, String userId, String photoGuid, MultipartFile file) {
        String extName = FileUtils.getExtName(file.getOriginalFilename());
        String photoName = photoGuid;
        if (null == photoName) {
            try {
                photoGuid = photoName = DigestUtils.md5DigestAsHex(file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(Result.FAILURE, "生成文件名称失败");
            }
        }
        photoName += extName;
        String filePath = String.format("%s/%s", configInfo.getUploadSubDir(configInfo.getBizDayDirRelPath(userId, "passport")), photoName);
        try {
            FileUtils.createFile(file.getInputStream(), new File(filePath));
            super.set("PHOTO:" + photoGuid, filePath);
            return new Result(Result.SUCC, photoGuid, "文件上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "文件上传失败");
        }
    }

    public Result savePassportFile(JSONObject data) {
        JSONArray photos = data.getJSONArray("photos");
        ArrayList<Integer> recorder = new ArrayList<Integer>();
        for (int i = 0; null != photos && i < photos.size(); i++) {
            JSONObject photo = photos.getJSONObject(i);
            String key = "PHOTO:" + photo.getString("photo");//图片缓存KEY
            String url = super.configInfo.getGAApiUrl("ReportPage/Upload.aspx", "materialGuid", photo.getString("typeId"), "userGuid", data.getString("userGuid"), "caseGuid", data.getString("caseGuid"), "projectGuid", data.getString("projectGuid"));
            String fileUrl = super.get(key);
            if (null == fileUrl) { //缓存KEY不存在
                recorder.add(i);
                continue;
            }
            int rt = doPostUpload(url, new File(fileUrl));
            if (HttpStatus.SC_OK != rt) {
                recorder.add(i);
            } else {
                super.delCache(key);
            }
        }
        return new Result(Result.SUCC, recorder, "上传成功");
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Result reportVehicleTempPassportInfo(JSONObject passportInfo, JSONObject lineInfo, JSONObject caseInfo, JSONObject filesInfo) throws IOException {
        String msg = null;
        Result result4 = savePassportFile(filesInfo);
        Result result1 = HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("ReportPage/ReportTXZ.aspx"), passportInfo);
        Result result2 = HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("ReportPage/ReportTXZ.aspx"), lineInfo);
        Result result3 = HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("ReportPage/ReportTXZ.aspx"), caseInfo);
        if (!result4.isSucc()) {
            msg += "图片信息上报失败：" + result4.getMsg() + ", ";
        }
        if (!result1.isSucc()) {
            msg += "通行证上报失败：" + result1.getMsg() + ", ";
        }
        if (!result2.isSucc()) {
            msg += "线路信息上报失败：" + result2.getMsg() + ", ";
        }
        if (!result3.isSucc()) {
            msg += "申报主信息上报失败：" + result3.getMsg() + ", ";
        }
        if (null == msg) {
            return new Result(Result.SUCC, "上报成功");
        } else {
            return new Result(Result.FAILURE, msg);
        }
    }

    @Override
    public Result loadConsultByPage(Query query, String userName) {
        int pageNum = query.getPageNum();
        int numPerPage = query.getNumPerPage();
        String keywords = query.getKeywords();
        StringBuilder url = new StringBuilder(configInfo.getServiceInterfaceAddress());
        url.append("/consults/myconsult/page?");
        url.append("pi=" + pageNum);
        url.append("&ps=" + numPerPage);
        url.append("&q_creator_s_eq=" + userName);
//        url.append(Strings.isNullOrEmpty(keywords) ? null : "q_creator_s_eq=" + keywords);
//        url.append("ispublic=" + ispublic);
//        url.append("status=" + status);
        System.out.println(url.toString());
        ApiPager<Consult> apiPager = HttpClientUtil.doGet(url.toString(), Consult.class);
        Result result = new Result();
        result.setSucc(Result.SUCC);
        result.setData(apiPager);
        result.setMsg("");
        result.setHasNext(apiPager.isHasNext());
        return result;
    }

    @Override
    public Result jbloadConsultByPage(Query query, String userGuid) {
        int pageNum = query.getPageNum();
        int numPerPage = query.getNumPerPage();
        StringBuilder url = new StringBuilder(configInfo.getServiceInterfaceAddress());
        url.append("/apphub/report/page?");
        url.append("ps=" + numPerPage);
        url.append("&pi=" + pageNum);
        url.append("&sb=" + "createdate");
        url.append("&sd=" + "desc");
        url.append("&q_userguid_s_eq=" + userGuid);
        if(!"0".equals(query.getProjectstatus())){
            url.append("&q_crstatus_s_eq=" + query.getProjectstatus());
        }else{
            url.append("&q_crstatus_s_eq=" + "");
        }

//        url.append(Strings.isNullOrEmpty(keywords) ? null : "q_creator_s_eq=" + keywords);
//        url.append("ispublic=" + ispublic);
//        url.append("status=" + status);
        System.out.println(url.toString());
        ApiPager<Xsjb> apiPager = HttpClientUtil.doGet(url.toString(), Xsjb.class);
        Result result = new Result();
        result.setSucc(Result.SUCC);
        result.setData(apiPager);
        result.setMsg("");
        result.setHasNext(apiPager.isHasNext());
        return result;
    }

    @Override
    public Result jbinfo(String guid)throws IOException  {

        String url = configInfo.getServiceInterfaceAddress() + "/apphub/report/"+guid;
        JSONObject object = JSON.parseObject(HttpClientUtil.doGet(url));
        System.out.println("apiPager.getList()="+HttpClientUtil.doGet(url));

        if(null!= object.getJSONObject("data")){
            return new Result(Result.SUCC,object.getJSONObject("data"));
        }

        return new Result(Result.FAILURE);
    }



    private int doPostUpload(String url, File file) {
        HttpPost httpPost = new HttpPost(url);
        HttpEntity httpEntity = MultipartEntityBuilder.create().addBinaryBody("file", file).build();
        try {
            httpPost.setEntity(httpEntity);
            CloseableHttpResponse response = HttpClientUtil.getClient().execute(httpPost);
            int statuscode = response.getStatusLine().getStatusCode();
            response.close();
            return statuscode;
        } catch (IOException e) {
            //记录日志
            e.printStackTrace();
            return 500;
        } finally {
            httpPost.abort();
            httpPost.releaseConnection();
        }
    }

  /*  @Override
    public Result loadApplyMataer(String caseId, String type) throws IOException {
        return getAllResult(super.configInfo.getGAApiUrl("CaseCenter/CaseMaterial.aspx", "caseguid", caseId, "type", type));
    }
*/

    @Override
    public Result loadApplyMataer(String caseId, String type) throws IOException {

        List<CaseMeterial> result = caseMeterialMapper.getCaseMeterialByCaseGuid(caseId);
        if (!result.isEmpty()) {
            return new Result(Result.SUCC, result);

        }
        return new Result(Result.FAILURE, "暂无数据");


    }

    @Override
    public Result loadCaseBasis(String caseId) throws IOException {

        List<CaseBasis> result = caseBasisMapper.getCaseBasisByCaseGuid(caseId);
        if (!result.isEmpty()) {
            return new Result(Result.SUCC, result);
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    @Override
    public Result loadLawyerMeetInfo(JSONObject obj) throws IOException {
        Result result = HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("ReportPage/ReportLSNew.aspx"), obj);
        String jsonStr = (String) result.getData();
        if (jsonStr != null) {
            JSONObject json = JSONObject.parseObject(jsonStr);
            json.put("msg", result.getMsg());
            result.setData(json.toString());
        } else {
            JSONObject json = new JSONObject();
            json.put("msg", result.getMsg());
            result.setData(json.toString());
        }
        return result;
    }

    @Override
    public Result uploadLawyerMeterial(MultipartHttpServletRequest request)
            throws IOException {
        String materialGuid = request.getParameter("materialGuid");
        String userguid = request.getParameter("userguid");
        String caseguid = request.getParameter("caseguid");
        String projectguid = request.getParameter("projectguid");
        String dbid = request.getParameter("dbid");
        List<MultipartFile> photos = request.getFiles("photo");
        ArrayList<Integer> recorder = new ArrayList<Integer>();
        String[] meterialGuids = materialGuid.split("@");
        for (int i = 0; null != photos && i < photos.size(); i++) {
            //获取图片本地存取路径
            String filePath = String.format("%s/%s", configInfo.getUploadSubDir(configInfo.getBizDayDirRelPath(userguid, "temp")), photos.get(i).getOriginalFilename());
            File file = new File(filePath);
            try {
                //将图片保存到本地
                FileUtils.createFile(photos.get(i).getInputStream(), file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //调用接口，将信息和图片传送过去
            String url = super.configInfo.getGAApiUrl("ReportPage/Upload.aspx", "materialGuid", meterialGuids[i], "userGuid", userguid, "caseGuid", caseguid, "projectGuid", projectguid, "dbid", dbid);
            int rt = doPostUpload(url, new File(filePath));
            //本地文件删除
            file.delete();
            if (HttpStatus.SC_OK != rt) {
                recorder.add(i);
            }
        }
        return new Result(Result.SUCC, recorder, "上传成功");
    }

    @Override
    public Result loadLawyerMeetAppointSub(JSONObject obj) throws IOException {
        Result result = HttpClientUtil.doGAUrlPost(super.configInfo.getGAApiUrl("ReportPage/ReportLSNew.aspx"), obj);
        return result;
    }

}
